import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from pathlib import Path


def main():
    # ==================== 配置参数 ====================
    INPUT_EXCEL = r"C:\Users\23248\PycharmProjects\stance\StanceDetectionLab\lab2\test_data\output.xlsx"
    OUTPUT_EXCEL = Path(INPUT_EXCEL).with_name(Path(INPUT_EXCEL).stem + "_filtered.xlsx")
    MAX_LENGTH = 300  # 文本长度阈值
    PLOT_IMG = "text_length_distribution_filtered.png"

    # ==================== 中文显示配置 ====================
    plt.rcParams.update({
        'font.family': 'SimSun',
        'axes.unicode_minus': False
    })

    try:
        # ==================== 数据加载与处理 ====================
        df = pd.read_excel(INPUT_EXCEL)
        df['text_length'] = df['content'].astype(str).apply(len)

        # 过滤长文本并保存
        filtered_df = df[df['text_length'] <= MAX_LENGTH]
        filtered_df.to_excel(OUTPUT_EXCEL, index=False)
        print(f"已保存过滤后数据至：{OUTPUT_EXCEL}")

        # ==================== 可视化配置 ====================
        fig, ax = plt.subplots(figsize=(12, 7), dpi=100)

        sns.histplot(filtered_df['text_length'],
                     bins=30,
                     kde=True,
                     color='#2E86C1',
                     edgecolor='white',
                     line_kws={'lw': 2},
                     alpha=0.8)

        # 添加统计标注
        mean_len = filtered_df['text_length'].mean()
        median_len = filtered_df['text_length'].median()
        plt.axvline(mean_len, color='#E74C3C', linestyle='--',
                    label=f'均值 ({mean_len:.1f})')
        plt.axvline(median_len, color='#28B463', linestyle='-.',
                    label=f'中位数 ({median_len:.1f})')

        # 图表元素设置
        plt.title(f'文本长度分布分析（≤{MAX_LENGTH}字符）', fontsize=14, pad=20)
        plt.xlabel('文本长度（字符数）', fontsize=12)
        plt.ylabel('出现频次', fontsize=12)
        plt.legend(fontsize=10)
        plt.grid(True, alpha=0.3)
        sns.despine()

        plt.tight_layout()
        plt.savefig(PLOT_IMG, bbox_inches='tight')
        print(f"已保存分布图至：{PLOT_IMG}")
        plt.show()

    except PermissionError:
        print(f"文件保存失败：请关闭正在使用的Excel文件")
    except Exception as e:
        print(f"操作失败：{str(e)}")


if __name__ == "__main__":
    main()